using System;
using System.Linq;
using TripleA.Core.Interfaces.Entities;

namespace TripleA.Core.Extensions.Process
{
    public class CheckProcessIsRunningStep<T> : StepBase<T>
        where T: Context
    {
        public bool ShouldBeRunning { get; set; }
        public string ExeFilename { get; set; }

        public CheckProcessIsRunningStep()
        {
            ShouldBeRunning = true;
        }

        public override void Execute(T context)
        {
            var found = System.Diagnostics.Process.GetProcesses().ToList()
                .Any(p => IsTargetProcess(p, ExeFilename));

            if (ShouldBeRunning && !found)
                throw new ApplicationException(string.Format("Executable image '{0}' is not running", ExeFilename));
            if (!ShouldBeRunning && found)
                throw new ApplicationException(string.Format("Executable image '{0}' is running; it should not be", ExeFilename));
        }

        protected virtual bool IsTargetProcess(System.Diagnostics.Process p, string targetFilename)
        {
            try
            {
                var result = (string.Compare(p.ProcessName, "System", StringComparison.InvariantCultureIgnoreCase) != 0) &&
                       (string.Compare(p.ProcessName, "Idle", StringComparison.InvariantCultureIgnoreCase) != 0) &&
                       p.MainModule.FileName.EndsWith(targetFilename, StringComparison.InvariantCultureIgnoreCase);
                return result;
            }
            catch
            {
                return false;
            }
        }
    }
}